<?php

namespace App\Http\Controllers\Admin;

use App\Models\Article;
use App\Models\ArticleCategory;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ArticleController extends Controller
{
    //
    public function index(){

        return view('admin.article.index');
    }

    public function indexPost(Request $request)
    {
        $input = $request->all();
        $condition = [
            'condition' => []
        ];
        $serach = [];
        if($request->has('serach_name')){
            //dd($request->input('serach_name'));
            $condition = [
                'condition' => [
                    [
                        'where',
                        ['where','title like %?%'],
                        ['orwhere','id = ?']
                    ]
                ]
            ];
            $serach = [
                $request->input('serach_name'),
                $request->input('serach_name')
            ];
        }
        $dd = (new Article())->dataTable10(['*'], $input ,$condition, $serach);
        return response()->json($dd);
    }

    /**
     *  添加文章
     */
    public function addArticle()
    {
        $all_cate = (new ArticleCategory())->arrayAllCate();

        return view('admin.article.addArticle',['allcate'=>$all_cate]);
    }

    public function addArticlePost(Request $request)
    {
        $input = [
            'title' => $request->input('title'),
            'description' => $request->input('description'),
            'author' => $request->input('author'),
            'from'  => $request->input('from'),
            'cate_id' => $request->input('cate_id'),
            'content' => $request->input('content')
        ];
        if($request->has('id')){
            $res = Article::find($request->input('id'))->update($input);
        }else{
            $res = Article::create($input);
        }
        if($res){
            return response()->json(['code'=>1, 'msg'=>'成功']);
        }else{
            return response()->json(['code'=>0, 'msg'=>'失败']);
        }
    }

    /**
     *  编辑文章
     */
    public function editArticle($id = 0)
    {
        $article_info = Article::find($id);
        $all_cate = (new ArticleCategory())->arrayAllCate();

        return view('admin.article.addArticle',['id'=>$id, 'allcate'=>$all_cate, 'article_info'=>$article_info]);
    }

    /**
     *  删除文章
     */
    public function delArticle(Request $request)
    {
        if($request->has('id')){
            $res = Article::find($request->input('id'))->delete();
            if($res){
                return response()->json(['code'=>1, 'msg'=>'成功']);
            }else{
                return response()->json(['code'=>0, 'msg'=>'失败']);
            }
        }
    }



}
